<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="base64s" :src="base64s" alt="" class="preview" />
      <img src="../../../assets/images/avatar.jpg" alt="" class="preview" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- <input type="file" style="display:none" /> -->
        <input type="file" accept="image/*" @change="toheadinfo" style="display: none" ref="iptRef" />
        <el-button type="primary" @click="tofile" size="small" icon="el-icon-plus">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="!Boolean(base64s)" @click="toArater"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { updAraterAPI } from '@/api/uers.js'
export default {
  name: 'UserAvatar',
  data() {
    return {
      base64s: ''
    }
  },
  methods: {
    tofile() {
      this.$refs.iptRef.click()
    },
    // 选择头像
    toheadinfo() {
      const files = this.$refs.iptRef.files
      console.dir(this.$refs.iptRef)
      if (files[length] === 0) {
      } else {
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = () => {
          this.base64s = fr.result
        }
      }
    },
    // 头像上传

    async toArater() {
      console.log(this.base64s)
      const { data: res } = await updAraterAPI(this.base64s)
      if (res.code !== 0) return this.$message.error('上传头像失败！')
      this.$message.success('上传头像成功！')
      this.$store.dispatch('uers/initUers')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
